<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use DB;
use Session;
use Mail;

class CheckController extends Controller
{
  
  /**
   * [Ajax验证]
   * @param Request $req [request对象]
   * @return [bool]      [通过验证返回true，没通过返回false]
   */
  public function Ajax(Request $req)
  {
    //ajax进来后,先获取验证类型
    $res = $req->input();     //$res  ['type'=>'value','input'=>'value'];
    $arr = ['user_name','user_nick','user_phone'];

    //调用正则,判断post数据是否符合正则
    if (in_array($res['type'], $arr)) {
       $matbool = $this->checkMatch($res['type'],$res['input']);
       $sqlbool = !$this->checkSql($res['type'],$res['input']);
       $bool = $matbool && $sqlbool;
   }

   return $bool?1:0;
  }

  public function checkLoginType(Request $req)
  {
      $res = $req->input();     //$res  ['type'=>'value','input'=>'value'];
      $uphone = DB::table('users')->select('user_id')->where('user_phone',$res['input'])->first();
      $uname = DB::table('users')->select('user_id')->where('user_name',$res['input'])->first();
      return $uphone||$uname ? 1:0;
  }

  /**
   * [正则验证]
   * @param  [string]  $type  [需要验证的正则类型]
   * @param  [string]  $input [需要正则验证的值]
   * @return [bool]           [返回正则验证的结果]
   */
  public function checkMatch($type,$input)
  {
    //判断用户名是否符合正则[用户名必须是小写字母和数字,在6~10位之间]
    if ($type=="user_name") {
      return preg_match('/[a-z0-9]{6,10}/', $input);
    }

    //判断用户密码是否符合正则[密码必须是字母和数字,在6~12位之间]
    elseif ($type=='user_password') {
      return preg_match('/[A-Za-z0-9]{6,12}/', $input);
    }

    //判断用户昵称是否符合正则[昵称必须是3到10位的字母或中文]
    elseif ($type=='user_nick') {
      return preg_match('/^[a-zA-Z\x{4e00}-\x{9fa5}]{3,10}$/u', $input);
    }

    //判断用户手机号是否符合正则[手机号格式不正确]
    elseif ($type=='user_phone') {
      return preg_match('/^1[34578]{1}\d{9}$/', $input);
    }

    //判断用户邮箱是否符合正则
    elseif ($type=="user_email") {
      return preg_match('/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/', $input);
    }
  }

  /**
   * [查看在数据库里是否存在]
   * @param  [string]  $type  [需要验证的sql类型]
   * @param  [string]  $input [需要sql验证的值]
   * @return [bool]          [返回sql验证的结果]
   */
  public function checkSql($type,$input)
  {
      //判断用户名是否存在
      if ($type == 'user_name') {
          return DB::table('users')->select('user_id')->where('user_name',$input)->first();
      }

      //判断昵称是否存在
      if ($type == 'user_nick') {
          return DB::table('users')->select('user_id')->where('user_nick',$input)->first();
      }

      //判断手机号是否存在
      if ($type == 'user_phone') {
          return DB::table('users')->select('user_id')->where('user_phone',$input)->first();
      }
  }

  /**
  * [生成验证码方法]
  * @return [img] [显示验证码]
  */
  public function verifyimg(Request $req)
  {
    //初始化图片验证码
    $builder = new CaptchaBuilder;
    $builder->setMaxAngle(5);
    $builder->build($width = 220, $height = 40);
    //获取验证码的字符串
    $verifyStr = $builder -> getPhrase();

    //将字符串存进session
    $req->session()->flash('captcha', $verifyStr);

    //生成图片
    header("Cache-Control: no-cache, must-revalidate");
    header('Content-Type: image/jpeg');
    $builder -> output();
  }

  /**
   * [验证图片验证码]
   * @param  Request $req [request对象]
   * @return [int]      [校验正确返回1，失败返回0]
   */
  public function checkimg(Request $req)
  {
    return Session::get('captcha')===$req->input('veryfy')?1:0;
  }


/*********************************start-短信验证码*********************************/
  public function checkmessage(Request $req)
  {
      $res = $req->input();
      $rand = mt_rand(100000,999999);
      $req->session()->flash('phonecode', $rand);
      return $this->yzm($res['input'],$rand);
  }

  /**
   * [手机验证码核心]
   * @param  [string]  $phone [用户手机号]
   * @param  [string]  $rand  [验证码]
   * @return {[type]        [description]
   */
  public function yzm($phone,$rand)
  {
      //设置头信息
      header("Content-Type:text/html;charset=utf-8");
      $apikey = "e6d2e62f77130101091e5d9572f839b5"; //
      $mobile = $phone; //要发送到的手机号
      $ch = curl_init();

      /* 设置验证方式 */
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));

      /* 设置返回结果为流 */
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      /* 设置超时时间*/
      curl_setopt($ch, CURLOPT_TIMEOUT, 10);

      /* 设置通信方式 */
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

      // 取得用户信息
      $json_data = $this->get_user($ch,$apikey);
      $user_array = json_decode($json_data,true);

      // 发送短信
      $data=array('tpl_id'=>'1751408','tpl_value'=>('#code#').'='.urlencode($rand),'apikey'=>$apikey,'mobile'=>$mobile);

      $json_data = $this->tpl_send($ch,$data);
      $data_array = json_decode($json_data,true);

      return $data_array['msg'];
  }

  public function get_user($ch,$apikey){
      curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/user/get.json');
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('apikey' => $apikey)));
      return curl_exec($ch);
  }

  function tpl_send($ch,$data){
      curl_setopt ($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/tpl_single_send.json');
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
      return curl_exec($ch);
  }

/**********************************end-短信验证码**********************************/

/*********************************start-邮箱验证码*********************************/
  public function checkemail(Request $req)
    {   $rand = mt_rand(100000,999999);
        $req->session()->flash('emailcode', $rand);
        $res = $req->input();
        $email = $res['input'];
        Session::put(['email'=>$email,'rand'=>$rand]);
        $bool = Mail::raw('您好欢迎加入煤球游戏对战平台,您的验证码是 : '.Session::get('rand'), function ($message) {
            $to = Session::get('email');
            $message ->to($to)->subject('欢迎注册煤球游戏对战平台');
        });
        return $bool ? 1 : 0;
    }
/*********************************end-邮箱验证码*********************************/
}
